//
//  HMMainViewController.m
//
//
//  Created by apple on 14-7-25.
//  Copyright (c) 2014年 heima. All rights reserved.
//

#import "HMMainViewController.h"
#import "CQViewController.h"

#import "HMNavigationController.h"
#import "SHServiceViewController.h"
#import "SHFeedbackTableViewController.h"
#import "SHMyAcountViewController.h"
#import "FMDB.h"


// 支付宝头文件
#import "AlixPayOrder.h"
#import "PartnerConfig.h"
#import "DataSigner.h"
#import "AlixLibService.h"
// 支付宝头文件

#import "UMFeedback.h"
#import "UMessage.h"

#import "UMFeedback.h"
#import "UMessage.h"


#import "MobClick.h"

#define HMNavShowAnimDuration 0.25
#define HMCoverTag 100



@interface HMMainViewController () <UITableViewDelegate,UITableViewDataSource>


/**
 *  正在显示的导航控制器
 */

@property (weak, nonatomic) IBOutlet UIImageView *headview;
@property (weak, nonatomic) IBOutlet UILabel *phoneno;
@property(nonatomic,strong) CQViewController *CQViewController;

/**
 *  菜单tableview
 */
@property (weak, nonatomic) IBOutlet UITableView *tableview;

@end

@implementation HMMainViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    if (IOS7)
    {
    self.tableview.height = 200;
    }
    //订阅通知(dianji)
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didSelected:) name:@"dianji" object:nil];
    
    
    
    //订阅通知（返回电话然后放到头像下边）
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setP:) name:@"LOGINED" object:nil];

    
    
    //添加tableview代理
    self.tableview.dataSource = self;
    self.tableview.delegate = self;
    [self.tableview setBackgroundColor:[UIColor clearColor]];
    
    
    
    
    
    
    //-----------sql----------------------------
    // 1.获得数据库文件的路径
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filename = [doc stringByAppendingPathComponent:@"youjian.sqlite"];
    
    
    // 2.得到数据库
    FMDatabase *db = [FMDatabase databaseWithPath:filename];
    if([db open])
    {
        
        FMResultSet *resultset =  [db executeQuery:@"select * from userinfo"];
        while ([resultset next]) {
            NSString *phone = [resultset stringForColumn:@"phone"];
           
            self.phoneno.text =[NSString cutPhoneWithPhoneno:phone];
        }
        
    }
    

    //-----------endSql-------------------------
    
    
    
    
    
    //添加各种控制器
    [self setUpMapView];
    
    self.tableview.bounces = NO;
    
}
-(void)setP:(NSNotification *)note
{
   NSDictionary *dic = (NSDictionary *) note.userInfo;
   NSString *phoneno =  dic[@"key"];
    self.phoneno.text = [NSString cutPhoneWithPhoneno:phoneno];
    
    
}

-(void)didSelected:(NSNotification *)note
{
    //这样就能取得key1中的值了(当然传对象类型也是可以的)
    NSString *value = note.userInfo[@"key"];//index ==1(服务条款) 2(意见反馈)
    int index = [value intValue];
    HMNavigationController *nv =  self.childViewControllers[index] ;
    
    [nv.view removeFromSuperview];
    
}

-(void)setUpMapView
{
    CQViewController *mapview = [[CQViewController alloc] init];
    

    self.CQViewController = mapview;
    HMNavigationController *nv = [[HMNavigationController alloc] initWithRootViewController:mapview];

    [self.view addSubview:nv.view];
    
    [self addChildViewController:nv];
    
    
    
    //添加服务信息控制器
    SHServiceViewController *service = [[SHServiceViewController alloc] init];
    HMNavigationController *nv2 = [[HMNavigationController alloc] initWithRootViewController:service];

    [self addChildViewController:nv2];
    
    //添加意见反馈控制器(index=2)
    
    //TODO: 改变意见反馈的 控制器

    SHFeedbackTableViewController *nvv = [[SHFeedbackTableViewController alloc] init];
    HMNavigationController *nvfeedback = [[HMNavigationController alloc] initWithRootViewController:nvv];
    [self addChildViewController:nvfeedback];
    
    

    
    
    
    
    //添加我的账户控制器(index=3)
    SHMyAcountViewController *myaccount = [[SHMyAcountViewController alloc] init];
    HMNavigationController *nvmyaccount = [[HMNavigationController alloc] initWithRootViewController:myaccount];
    [self addChildViewController:nvmyaccount];
    
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}
- (IBAction)cancelLogin:(UIButton *)sender {

    
    NSString *doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *filename = [doc stringByAppendingPathComponent:@"youjian.sqlite"];
    
    FMDatabase *db = [FMDatabase databaseWithPath:filename];
    if ([db open])
    {
        [db executeUpdate:@"delete from userinfo"];
        [db commit];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"SIGNOUT" object:nil];
    }
    
    /*
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"退出登录" message:@"是否确定要退出登录?" preferredStyle:UIAlertControllerStyleAlert];
    
    // Create the actions.
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        NSLog(@"The \"Okay/Cancel\" alert's cancel action occured.");
    }];
    
    
    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
       
        NSString *doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
        NSString *filename = [doc stringByAppendingPathComponent:@"youjian.sqlite"];
        
        FMDatabase *db = [FMDatabase databaseWithPath:filename];
        if ([db open])
        {
            [db executeUpdate:@"delete from userinfo"];
            [db commit];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"SIGNOUT" object:nil];
        }
        
    }];
    
    
    // Add the actions.
    [alertController addAction:cancelAction];
    [alertController addAction:otherAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
    
    
    
    
  


    */
    
}
#pragma mark -uitableDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;
    
    
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
    
    if(indexPath.row == 0)
    {
        cell.textLabel.text = @"我的账户";
        cell.accessoryType  = UITableViewCellAccessoryDisclosureIndicator;
        
        //TODO: 设置红点
        UIImageView *imageview = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"notifications"]];
        imageview.frame = CGRectMake(10, 10, 8, 8);
        [cell addSubview:imageview];
    }
    
    else if (indexPath.row == 1)
    {
        cell.textLabel.text = @"服务条款";
        cell.accessoryType  = UITableViewCellAccessoryDisclosureIndicator;
    }
    else if (indexPath .row ==2)
    {
        cell.textLabel.text = @"意见反馈";
        cell.accessoryType  = UITableViewCellAccessoryDisclosureIndicator;
    }
    else if (indexPath .row ==3)
    {
        cell.textLabel.text = @"检查更新";

        UILabel *versionNo = [[UILabel alloc] initWithFrame:CGRectMake(210, 22, 40, 14)];
        versionNo.textColor = HMColor(231, 231, 231);
        versionNo.text = @"V1.1";
        [cell addSubview:versionNo];
    }
    
    
    //设置cell透明
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.backgroundColor = [UIColor clearColor];
    
    cell.contentView.backgroundColor = [UIColor clearColor];
    
    UIView *backView = [[UIView alloc] initWithFrame:CGRectZero];
    
    backView.backgroundColor = [UIColor clearColor];
    
    cell.backgroundView = backView;
    
    return cell;
}


/**
 *  选中cell
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if(indexPath.row == 0)
    {
        HMNavigationController *nvv = self.childViewControllers[3];
        [self.view addSubview: nvv.view];
        
        
    }
    else if(indexPath.row == 1)//服务条款
    {
        
        HMNavigationController *nvv = self.childViewControllers[1];
        [self.view addSubview: nvv.view];
      
          //TODO: 添加检测更新功能
        /*
         NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
         [request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://itunes.apple.com/lookup?id=%@",@"515624508"]]];//SHAPPID
         
         
         //TODO: 获取版本号
         [request setHTTPMethod:@"GET"];
         NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
         NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:returnData options:0 error:nil];
         NSArray *dic = (NSArray *)jsonData[@"results"];
         NSString *newVersion = ((NSDictionary *) dic[0])[@"version"];
         HMLog(@"new version is %@",newVersion);
         
         
         NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
         NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
         
         HMLog(@"my version is %@",app_Version);
         */
         
        
        //[MobClick checkUpdate:@"New version" cancelButtonTitle:@"Skip" otherButtonTitles:@"Goto Store"];

        
        
    }
    else if (indexPath .row ==2)//意见反馈
    {
        
        HMNavigationController *nvv = self.childViewControllers[2];
        [self.view addSubview: nvv.view];


    }
    else if (indexPath .row ==3)
    {
        
        [MobClick checkUpdateWithDelegate:self selector:@selector(fuck:)];
        
        
    }
    else if (indexPath .row ==4)//退出登录
    {
        //已经废弃
        
        
        
        
    }
    
}
-(void)fuck:(NSDictionary *)dic
{

    if ([dic[@"update"] isEqualToString:@"NO" ])
    {
        MBProgressHUD  *HUD = [[MBProgressHUD alloc] initWithView:self.view];
        [self.view addSubview:HUD];
        HUD.labelText =@"已经是最新版本";
        HUD.mode = MBProgressHUDModeText;
        
        [HUD showAnimated:YES whileExecutingBlock:^{
            sleep(1.5);
        } completionBlock:^{
            [HUD removeFromSuperview];
        }];
    }
    else
    {
        HMLog(@"有更新");
    }
    
}

/**
 *  cell高度
 */
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
    

    
    
}



@end